--
-- Author: shunguo.chen
-- Date: 2017-09-12 10:12:11
--
-- RoleRender 对 Res.BaseRole 的解析

local AvatarIconNode = require("app.widget.AvatarIconNode")

local ClassRef = app.mvc.createRenderClass(...)

-- data = UserBaseInfo like
function ClassRef.createWithData(data, node)
	local sprite = ClassRef.extend(node or cc.CSLoader:createNode(Res.BaseRole))
	if node == nil then
		ccui.Helper:doLayout(sprite)
	end
	sprite:init(data)
	return sprite
end

function ClassRef.create(node)
	local sprite = ClassRef.extend(node or cc.CSLoader:createNode(Res.BaseRole))
	if node == nil then
		ccui.Helper:doLayout(sprite)
	end
	sprite:init()
	return sprite
end

function ClassRef:init(data)
	self.super.init(self, data)

	self:setContentSize(self._ui.Panel:getContentSize())
	self:setSelected(false)
	self._ui.bg:setPressedActionEnabled(false)
	self._ui.bg:addClickEventListener(function()
		if not self:isSelected() then
			executeFunc(self._onBtnClick, self)
		end
	end)

	self._avatarIcon = AvatarIconNode.new(self._ui.Panel, "icon")

	self:refresh()
end

function ClassRef:refresh()
	local hasData = self._data ~= nil
	if self._ui.more then
		self._ui.more:setVisible(not hasData)
	end
	if self._ui.Panel_lv then
		self._ui.Panel_lv:setVisible(hasData)
	end
	if self._ui.class_icon then
		self._ui.class_icon:setVisible(hasData)
	end
	if self._ui.name then
		self._ui.name:setVisible(hasData)
	end

	if self._data then
		if self._ui.num then
			self._ui.num:setString(self._data.level)
		end
		if self._ui.name then
			self._ui.name:setString(self._data.name)
		end
		if self._ui.class_icon then
			self._ui.class_icon:loadTexture(GD:getClassIcon(self._data.classID, 2))
		end
		self._avatarIcon:update(self._data)
	else
		self._avatarIcon:hide()
	end
end

function ClassRef:setLock(b)
	self._ui.lock:setVisible(b)
end

function ClassRef:isLock()
	return self._ui.lock:isVisible()
end

function ClassRef:onTouch(cb)
	self._onTouch = cb
end

function ClassRef:isSelected()
	return not self._ui.bg:isBright()
end

function ClassRef:setSelected(b)
	self._ui.bg:setBright(not b)
	if b and self._onTouch then
		self._ui.bg:addTouchEventListener(
			function(sender,eventType)
	            if eventType == ccui.TouchEventType.began then
	                self._touchTime = os.time()
	                self:performWithDelay(function()
	                		executeFunc(self._onTouch, self)
	                	end, 1)
	            elseif eventType == ccui.TouchEventType.canceled then
	                self:stopAllActions()
	            elseif eventType == ccui.TouchEventType.ended then
	                if (os.time() - self._touchTime) < 1 then
			            self:stopAllActions()
	                end
	            end
        	end
        )
    else
    	self._ui.bg:addTouchEventListener(function() end)
	end
end

function ClassRef:onBtnClick(cb)
	self._onBtnClick = cb
end

return ClassRef